package tcp

import (
	"fmt"
	"time"

	"go-micro.dev/v4"
	"go-micro.dev/v4/server"
	"signal/bll"
	"signal/config"
	"signal/lib/tcp"
	"signal/utils"
)

var (
	tcpName           string
	defaultListenAddr = ":7777"
	srv               server.Server
)

func Init() micro.Option {
	tcpName = config.Conf.Name + "-tcp"

	if config.Conf.TcpListen != "" {
		srv = tcp.NewServer(server.Address(fmt.Sprintf("%s", config.Conf.TcpListen)))
	} else {
		srv = tcp.NewServer(server.Address(fmt.Sprintf("0.0.0.0:%v", defaultListenAddr)))
	}

	s := srv.(*tcp.Server)
	s.RegisterHandler(bll.Handler)
	go func() {
		select {
		case <-config.ExitC:
			srv.Stop()
			return
		default:
		}
	}()
	utils.Throw(s.Start())

	if config.Conf.Traefik.Enabled {
		go func() {
			defer utils.ExceptionCatch()
			time.Sleep(time.Second * 5)
			fmt.Println("----------------------- 开始注册到 traefix --------------")
			utils.Throw(config.Register(tcpName, srv))
			fmt.Println("----------------------- 注册traefix 完成  --------------")
		}()

	}
	return micro.Server(srv)
}
